package com.itheima.filter;


import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.util.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class BackendFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        //获取当前的请求地址
        String uri=req.getRequestURI();
/*        System.out.println("来到过滤器了uri = " + uri);
        System.out.println("backend");*/
        /*
        判断请求地址是不是直接放行地址

         */
        if (uri.contains("login")||uri.contains("images")||uri.contains("plugins")
                ||uri.contains("styles")||uri.endsWith(".js")||uri.endsWith(".ico")
                ||uri.contains("front")||uri.contains("sms")||uri.contains("sendCode")){
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }

        HttpSession session = req.getSession();

        Employee employee=(Employee)session.getAttribute("employee");

        if (employee!=null){
            BaseContext.setCurrentId(employee.getId());
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }
        User user = (User) session.getAttribute("user");

        if (user!=null){
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }
        resp.sendRedirect("/backend/page/login/login.html");
    }
}
